<template>
  <div class="app-container">
    <!-- 上半部分：搜索和采购订单表格 -->
    <div class="top-section">
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="queryParams" class="search-form" size="small">
        <el-form-item label="采购编号">
          <el-input v-model="queryParams.po_code" placeholder="请输入采购编号" clearable />
        </el-form-item>
        <el-form-item label="采购名称">
          <el-input v-model="queryParams.po_name" placeholder="请输入采购名称" clearable />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input v-model="queryParams.supplier_name" placeholder="请输入供应商名称" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
            <el-option label="待提交" value="1" />
            <el-option label="采购中" value="2" />
            <el-option label="到货" value="3" />
            <el-option label="已上架" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div class="operation-buttons">
        <div class="left-buttons">
          <el-button type="primary" plain @click="handleAdd">
            <i class="el-icon-plus"></i> 新增
          </el-button>
          <el-button type="danger" plain :disabled="!pendingDeleteRows.length" @click="handleBatchDelete">
            <i class="el-icon-delete"></i> 批量删除
          </el-button>
        </div>
        <div class="top-right-btn">
          <el-button icon="el-icon-search" circle />
          <el-button icon="el-icon-refresh" circle @click="getList" />
        </div>
      </div>

      <!-- 采购订单表格 -->
      <el-table
        v-loading="loading"
        :data="orderList"
        @selection-change="handleSelectionChange"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="po_code" label="采购编号" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-link type="primary" @click="handleViewDetails(scope.row)">{{ scope.row.po_code }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="po_name" label="采购名称" align="center" show-overflow-tooltip />
        <el-table-column prop="supplier_name" label="供应商名称" align="center" show-overflow-tooltip />
        <el-table-column prop="purchase_date" label="采购日期" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.purchase_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="expected_delivery_date" label="期望交货日期" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.expected_delivery_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="total_amount" label="订单总金额" align="center">
          <template slot-scope="scope">
            ¥{{ formatCurrency(scope.row.total_amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="purchase_type" label="采购类型" align="center" />
        <el-table-column prop="create_time" label="创建时间" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="{ row }">
            <template v-if="row.status === '1'">
              <el-button type="text" @click="handleEdit(row)">
                <i class="el-icon-edit"></i> 修改
              </el-button>
              <el-button type="text" @click="handleDelete(row)">
                <i class="el-icon-delete"></i> 删除
              </el-button>
              <el-button type="text" @click="handleSubmit(row)">
                <i class="el-icon-check"></i> 提交
              </el-button>
            </template>
            <template v-else>
              ---
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 采购订单分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      :visible.sync="detailsVisible"
      width="70%"
      append-to-body
      :show-close="false"
    >
      <div slot="title" style="display: flex; justify-content: space-between; align-items: center;">
        <span class="el-dialog__title">采购订单详情</span>
        <el-button icon="el-icon-close" @click="detailsVisible = false" circle></el-button>
      </div>
      <div v-if="currentOrder">
        <el-descriptions title="订单信息" :column="3" border>
          <el-descriptions-item label="采购编号">{{ currentOrder.po_code }}</el-descriptions-item>
          <el-descriptions-item label="采购名称">{{ currentOrder.po_name }}</el-descriptions-item>
          <el-descriptions-item label="供应商">{{ currentOrder.supplier_name }}</el-descriptions-item>
          <el-descriptions-item label="批次号">{{ currentOrder.batch_code }}</el-descriptions-item>
          <el-descriptions-item label="期望交货日期">{{ formatDate(currentOrder.expected_delivery_date) }}</el-descriptions-item>
          <el-descriptions-item label="订单总金额">¥{{ formatCurrency(currentOrder.total_amount) }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.status)">{{ getStatusText(currentOrder.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="采购类型">{{ currentOrder.purchase_type }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(currentOrder.create_time) }}</el-descriptions-item>
        </el-descriptions>

        <h3 style="margin-top: 20px;">商品信息</h3>
        <el-table :data="pagedOrderDetails" v-loading="detailsLoading">
          <el-table-column prop="goods_code" label="物料编码" align="center"></el-table-column>
          <el-table-column prop="goods_name" label="物料名称" align="center"></el-table-column>
          <el-table-column prop="quantity_num" label="采购数量" align="center"></el-table-column>
          <el-table-column prop="unit_price" label="采购单价" align="center"></el-table-column>
          <el-table-column prop="total_price" label="总价" align="center"></el-table-column>
        </el-table>

        <pagination
          v-show="orderDetailsTotal > 0"
          :total="orderDetailsTotal"
          :page.sync="detailsPage.pageNum"
          :limit.sync="detailsPage.pageSize"
          @pagination="handleDetailsPageChange"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"
import { listPurchaseOrders, deletePurchaseOrder, batchDeletePurchaseOrders, submitPurchaseOrder, selectOrderLine_id } from "@/views/ck/js/purchase"


export default {
  name: 'PurchaseOrder',
  components: {
    Pagination
  },
  data() {
    return {
      loading: false,
      selectedRows: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        po_code: undefined,
        po_name: undefined,
        supplier_name: undefined,
        status: undefined
      },
      orderList: [],
      total: 0,
      detailsVisible: false,
      currentOrder: null,
      orderDetails: [],
      detailsLoading: false,
      detailsPage: {
        pageNum: 1,
        pageSize: 10
      }
    }
  },
  computed: {
    // 计算属性：只获取待提交状态的订单用于删除
    pendingDeleteRows() {
      return this.selectedRows.filter(row => row.status === '1');
    },
    pagedOrderDetails() {
      const start = (this.detailsPage.pageNum - 1) * this.detailsPage.pageSize;
      const end = start + this.detailsPage.pageSize;
      return this.orderDetails.slice(start, end);
    },
    orderDetailsTotal() {
      return this.orderDetails.length;
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listPurchaseOrders(this.queryParams).then(response => {
        this.orderList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(error => {
        console.error('获取采购订单列表失败:', error)
        this.loading = false
        this.$message.error('获取数据失败')
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      pageNum: 1,
      this.queryParams = {
        pageSize: 10,
        po_code: undefined,
        po_name: undefined,
        supplier_name: undefined,
        status: undefined
      }
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    handleAdd() {
      this.$router.push('/ck/PurchaseOrder/addOrder')
    },
    handleEdit(row) {
      // 跳转到新增页面，带上当前点击订单
      this.$router.push({
        path: '/ck/PurchaseOrder/updateOrder',
        query: { order: JSON.stringify(row) }
      })
    },
    handleDelete(row) {
      this.$confirm(`确认删除采购订单"${row.po_name}"吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePurchaseOrder(row.po_id).then(response => {
          if (response.flag) {
            this.$message.success('删除成功')
            this.getList()
          } else {
            this.$message.error(response.msg || '删除失败')
          }
        }).catch(error => {
          console.error('删除采购订单失败:', error)
          this.$message.error('删除失败')
        })
      }).catch(() => {})
    },
    handleViewDetails(row) {
      this.currentOrder = row;
      this.detailsVisible = true;
      this.detailsLoading = true;
      selectOrderLine_id(row.po_id).then(response => {
        this.orderDetails = response.rows || [];
        this.detailsLoading = false;
      }).catch(error => {
        console.error("获取订单详情失败:", error);
        this.detailsLoading = false;
        this.$message.error("获取订单详情失败");
      });
    },
    handleDetailsPageChange() {
      // This method is just to trigger re-computation of pagedOrderDetails
    },
    // 新增批量删除方法
    handleBatchDelete() {
      const pendingRows = this.pendingDeleteRows;
      if (pendingRows.length === 0) {
        this.$message.warning('没有可删除的待提交订单');
        return;
      }

      // 获取要删除的订单名称列表
      const orderNames = pendingRows.map(row => row.po_name);
      // 如果订单数量多于3个，只显示前3个，其余用"等"表示
      const displayNames = orderNames.length > 3 
        ? orderNames.slice(0, 3).join('、') + `等${orderNames.length}个订单` 
        : orderNames.join('、');
        
      this.$confirm(`确认删除以下待提交订单吗？<br/><br/>${displayNames}`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        // 提取所有待删除订单的ID，构造成数组格式
        const poIds = pendingRows.map(row => row.po_id);
        this.batchDeletePurchaseOrders(poIds);
      }).catch(() => {});
    },

    // 批量删除订单的API调用
    batchDeletePurchaseOrders(poIds) {
      this.loading = true;
      // 使用导入的API函数
      batchDeletePurchaseOrders(poIds).then(response => {
        this.loading = false;
        if (response.code === 200) {
          this.$message.success('批量删除成功');
          this.getList();
        } else {
          this.$message.error(response.msg || '批量删除失败');
        }
      }).catch(error => {
        this.loading = false;
        console.error('批量删除采购订单失败:', error);
        this.$message.error('批量删除失败');
      });
    },
    handleSubmit(row) {
      this.$confirm(`确认提交采购订单"${row.po_name}"吗？提交后将无法修改或删除`, '提交确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在提交订单，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        submitPurchaseOrder(row.po_id).then(response => {
          loading.close();
          if (response.code === 200) {
            this.$message.success('采购订单提交成功');
            this.getList(); // 刷新列表
          } else {
            this.$message.error(response.msg || '采购订单提交失败');
          }
        }).catch(error => {
          loading.close();
          console.error('提交采购订单失败:', error);
          this.$message.error('提交采购订单失败，请稍后重试');
        });
      }).catch(() => {});
    },
    formatDate(dateStr) {
      if (!dateStr) return ''
      return new Date(dateStr).toLocaleDateString()
    },
    formatNumber(num) {
      if (num === null || num === undefined) return '0'
      return Number(num).toLocaleString()
    },
    formatCurrency(num) {
      if (num === null || num === undefined) return '0.00'
      return Number(num).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },
    getStatusType(status) {
      const statusMap = {
        '1': 'info',
        '2': 'primary',
        '3': 'success',
        '4': 'success'
      }
      return statusMap[status] || 'info'
    },
    getStatusText(status) {
      const statusMap = {
        '1': '待提交',
        '2': '采购中',
        '3': '到货',
        '4': '已上架'
      }
      return statusMap[status] || '未知'
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.top-section {
  margin-bottom: 30px;
  width: 100%;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
}

.operation-buttons {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.left-buttons {
  display: flex;
  gap: 5px;
}

.top-right-btn {
  display: flex;
  gap: 10px;
}

.el-table {
  margin-bottom: 20px;
  width: 100% !important;
}

.el-table th {
  background-color: #f5f7fa;
}

/* 确保表格容器也是100%宽度 */
.el-table__body-wrapper {
  width: 100%;
}

.el-table__header-wrapper {
  width: 100%;
}

/* 操作列紧贴右边界 */
.el-table .el-table__cell:last-child {
  padding-right: 0 !important;
}

.el-table .el-table__cell:last-child .cell {
  padding-right: 10px !important;
}

/* 确保操作按钮在操作列中右对齐 */
.el-table .el-table__cell:last-child .cell {
  text-align: right !important;
}
</style> 